#include "AnimationManager.h"

DECLARE_SINGLETON_MEMBER(AnimationManager);

AnimationManager::AnimationManager(){}

AnimationManager::~AnimationManager()
{

}

bool AnimationManager::initAnimationMap()
{
	char temp[20];
	sprintf(temp, "%d", aDown);
	CCAnimationCache::sharedAnimationCache()->addAnimation(createHeroMovingAnimationByDirection(gDOWN), temp);
	sprintf(temp, "%d", aRight);
	CCAnimationCache::sharedAnimationCache()->addAnimation(createHeroMovingAnimationByDirection(gRIGHT), temp);
	sprintf(temp, "%d", aLeft);
	CCAnimationCache::sharedAnimationCache()->addAnimation(createHeroMovingAnimationByDirection(gLEFT), temp);
	sprintf(temp, "%d", aUp);
	CCAnimationCache::sharedAnimationCache()->addAnimation(createHeroMovingAnimationByDirection(gUP), temp);
	
	sprintf(temp, "%d", aFight);
	CCAnimationCache::sharedAnimationCache()->addAnimation(createFightAnimation(), temp);

	return true;
}

CCAnimation *AnimationManager::createHeroMovingAnimationByDirection(Direction direction)
{
	CCTexture2D *heroTexture = CCTextureCache::sharedTextureCache()->addImage("hero.png");
	CCSpriteFrame *frame0,*frame1,*frame2,*frame3;
	frame0 = CCSpriteFrame::createWithTexture(heroTexture, cocos2d::CCRect(32*0,32*direction,32,32));
	frame1 = CCSpriteFrame::createWithTexture(heroTexture, cocos2d::CCRect(32*1,32*direction,32,32));
	frame2 = CCSpriteFrame::createWithTexture(heroTexture, cocos2d::CCRect(32*2,32*direction,32,32));
	frame3 = CCSpriteFrame::createWithTexture(heroTexture, cocos2d::CCRect(32*3,32*direction,32,32));

	CCArray *animFrames = new CCArray(4); 
    animFrames->addObject(frame0); 
    animFrames->addObject(frame1); 
    animFrames->addObject(frame2); 
    animFrames->addObject(frame3); 
	CCAnimation *animation = new CCAnimation();
	animation->initWithSpriteFrames(animFrames, 0.05f); 
    animFrames->release();  

	return animation;
}

CCAnimation *AnimationManager::createFightAnimation()
{
	int fightAnim[] = { 4,6,8,10,13,15,17,19,20,22 };
	CCArray *animFrames = new CCArray();
	CCTexture2D * texture = CCTextureCache::sharedTextureCache()->addImage("sword.png");
	CCSpriteFrame *frame;
	int x,y;
	for (int i=0;i<10;i++)
	{
		x = fightAnim[i]%5-1;
		y = fightAnim[i]/5;
		frame = CCSpriteFrame::createWithTexture(texture, CCRect(192*x, 192*y, 192, 192));
		if ( fightAnim[i] == 17 || fightAnim[i] == 19)
			frame->setOffsetInPixels(ccp(0,-8));
		animFrames->addObject(frame);
	}
	CCAnimation *anim = new CCAnimation();
	anim->initWithSpriteFrames(animFrames, 0.1f);
	animFrames->release();

	return anim;
}

CCAnimation *AnimationManager::getAnimation(int key)
{
	char temp[20];
	sprintf(temp, "%d", key);
	return CCAnimationCache::sharedAnimationCache()->animationByName(temp);
}

CCAnimate *AnimationManager::createAnimate(int key)
{
	CCAnimation *anim = getAnimation(key);
	if(anim)
	{
		return CCAnimate::create(anim);
	}
	return NULL;
}